package com.example.android11_udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;



import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class MainActivity extends Activity implements OnClickListener {

	TextView retMsg;
	EditText sendMsg;
	Button send;
	String rMsg;
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		StrictMode.ThreadPolicy policy =
				new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		retMsg = (TextView) findViewById(R.id.retMsg);
		sendMsg = (EditText) findViewById(R.id.sendMsg);
		send = (Button) findViewById(R.id.send);
		send.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		start();
		retMsg.setText(rMsg);
	}
	private void start()
	{
		try{
			InetAddress iaddress = InetAddress.getByName("211.183.2.174");
			DatagramSocket dsocket = new DatagramSocket(3000);
			String sendData = sendMsg.getText().toString();
			byte[] sendBuffer = sendData.getBytes();
			DatagramPacket dpacket =  new DatagramPacket(
					sendBuffer, sendBuffer.length,iaddress,4000);
			
			dsocket.send(dpacket);
			byte[] reciveBuffer = new byte [600];
			dpacket = new DatagramPacket(reciveBuffer, reciveBuffer.length);
			dsocket.receive(dpacket);
			rMsg = new String(dpacket.getData());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
